<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use Hash;

use App\Http\Requests;
use App\Http\Controllers\Controller;
// use App\Http\Requests\InsertArticleRequest;
use App\Http\Requests\UserRequest;
class UserController extends Controller
{
    public function getIndex()
    {
    	
    	return view('shangcheng.admin.index');

    }


    public function getAdd()
    {
    	return view('shangcheng.user.add');
    }


    public function postDoadd(UserRequest $Request)
    {
    	dd($Request->all());

    	$data=$Request->except('_token');

    	//dd($data);

    	$data['password']=hash::make($data['password']);

    	$data['photo']=$this->upload($Request);
    	//dd($data['photo']);

    	if(!$data['photo'])
    	{
    		return redirect('admin/user/add')->with('error','请上传图片');
    	}

    	$res=DB::table('user')->insertGetId($data);

    	if($res){

    		return redirect('admin/user/index')->with('success','添加成功');
    		// echo 1;
    	}else{

    		return back()->with('error','添加失败');
    		// echo 0;
    	}
        

    }

    public function upload($Request)
    {	

    	
    	if($Request->hasFile('photo'))
    	{
    		$name=md5($Request['photo']).time();
            
    		$su=$Request->file('photo')->getClientOriginalExtension();
    		$Request->file('photo')->move('./shangcheng/uploads',$name.'.'.$su);
    		return '/shangcheng/uploads/'.$name.'.'.$su;
    	}
    }

    public function getSelect(Request $request)
    {
        $num=$request->input('num',10);
          
        if($request->has('title'))
        {   
            
            $users=DB::table('user')->where('name','like','%'.$request->input('title').'%')->paginate($num);
        }else{
            
           $users=DB::table('user')->paginate($num);
        }
        
        $data=$request->only('num','title');

    	return view('shangcheng.user.index',['users'=>$users,'data'=>$data]);
    }


    public function postDelete(Request $request)
    {
    	$id=$request->input('id');

    	$res=DB::table('user')->where('id',$id)->delete();

    	echo $res;
    }

    public function getUpdate($id)
    {

    	$data=DB::table('user')->where('id',$id)->first();
        
    	return view('shangcheng.user.update',['data'=>$data]);
    }

    public function postDoupdate(Request $request)
    {

    	$data=$request->except('id','_token');

    	$data['password']=hash::make($data['password']);
    	
    	$data['photo']=$this->upload($request);
		
		$id=$request->input('id');
    	
    	// if(!$data['photo'])
    	// {
    	// 	return redirect('/admin/user/update',['id'=>$id])->with('error','请上传图片');
    	// }

    	
    	
    	$res=DB::table('user')->where('id',$id)->update($data);

    	if($res){

    		return redirect('/admin/user/select')->with('success','修改成功');
    	}else{
    		return redirect('/admin/user/update',['id'=>$id])->with('error','修改失败');
    	}



    }

}
